// Hash Generator 渲染器
window.HashGeneratorRenderer = class HashGeneratorRenderer {
    static getHTML() {
        return `
            <div class="flex items-center justify-between mb-6">
                <h2 class="text-3xl font-bold text-gray-800">哈希生成工具</h2>
                <div class="flex items-center space-x-4">
                    <div class="text-sm text-gray-500">
                        <span id="hash-status" class="font-medium">就绪</span>
                    </div>
                </div>
            </div>

            <!-- 模式选择 -->
            <div class="bg-gray-50 border rounded-lg p-4 mb-6">
                <div class="flex items-center space-x-6 mb-4">
                    <label class="inline-flex items-center">
                        <input type="radio" class="form-radio text-blue-600" name="hash-mode" value="text" checked>
                        <span class="ml-2 font-medium">文本哈希</span>
                    </label>
                    <label class="inline-flex items-center">
                        <input type="radio" class="form-radio text-blue-600" name="hash-mode" value="file">
                        <span class="ml-2 font-medium">文件哈希</span>
                    </label>
                    <label class="inline-flex items-center">
                        <input type="radio" class="form-radio text-blue-600" name="hash-mode" value="verify">
                        <span class="ml-2 font-medium">哈希验证</span>
                    </label>
                    <label class="inline-flex items-center">
                        <input type="radio" class="form-radio text-blue-600" name="hash-mode" value="batch">
                        <span class="ml-2 font-medium">批量生成</span>
                    </label>
                </div>

                <!-- 算法选择 -->
                <div class="flex items-center space-x-4 mb-4">
                    <label class="text-sm font-medium text-gray-700">哈希算法:</label>
                    <select id="hash-algorithm" class="form-select text-sm border-gray-300 rounded-md">
                        <option value="md5">MD5</option>
                        <option value="sha1">SHA-1</option>
                        <option value="sha256" selected>SHA-256</option>
                        <option value="sha512">SHA-512</option>
                    </select>
                </div>
                
                <!-- 工具栏 -->
                <div class="flex flex-wrap items-center gap-3">
                    <button id="generate-hash" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center">
                        <i data-feather="hash" class="w-4 h-4 mr-2"></i>
                        生成哈希
                    </button>
                    <button id="verify-hash" class="bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center">
                        <i data-feather="check-circle" class="w-4 h-4 mr-2"></i>
                        验证哈希
                    </button>
                    <button id="compare-files" class="bg-purple-600 hover:bg-purple-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center">
                        <i data-feather="layers" class="w-4 h-4 mr-2"></i>
                        文件对比
                    </button>
                    <button id="copy-hash" class="bg-gray-600 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center" disabled>
                        <i data-feather="copy" class="w-4 h-4 mr-2"></i>
                        复制结果
                    </button>
                    <button id="clear-hash" class="bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center">
                        <i data-feather="trash-2" class="w-4 h-4 mr-2"></i>
                        清空
                    </button>
                </div>
            </div>

            <!-- 内容区域 -->
            <div class="grid md:grid-cols-2 gap-6">
                <!-- 输入区域 -->
                <div>
                    <!-- 文本输入模式 -->
                    <div id="hash-text-mode">
                        <h3 class="text-lg font-semibold text-gray-700 mb-3 flex items-center">
                            <i data-feather="edit-3" class="w-5 h-5 mr-2"></i>
                            输入文本
                        </h3>
                        <textarea id="hash-input" class="w-full h-48 p-4 border border-gray-300 rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="请输入要生成哈希值的文本..."></textarea>
                        <div class="mt-2 text-sm text-gray-500">
                            字符数: <span id="hash-input-count">0</span>
                        </div>
                    </div>

                    <!-- 文件输入模式 -->
                    <div id="hash-file-mode" class="hidden">
                        <h3 class="text-lg font-semibold text-gray-700 mb-3 flex items-center">
                            <i data-feather="file" class="w-5 h-5 mr-2"></i>
                            选择文件
                        </h3>
                        <div id="hash-file-drop" class="w-full h-48 border-2 border-dashed border-gray-300 rounded-lg flex flex-col items-center justify-center cursor-pointer hover:border-blue-500 hover:bg-blue-50 transition duration-200">
                            <i data-feather="upload-cloud" class="w-12 h-12 text-gray-400 mb-4"></i>
                            <p class="text-gray-600 text-center">
                                <span class="font-medium">点击选择文件</span><br>
                                或拖拽文件到此处<br>
                                <span class="text-sm text-gray-500">支持最大100MB文件</span>
                            </p>
                        </div>
                        <input type="file" id="hash-file-input" class="hidden">
                        <div id="hash-file-info" class="mt-3 text-sm text-gray-600 hidden">
                            文件: <span id="hash-file-name"></span> | 
                            大小: <span id="hash-file-size"></span>
                        </div>
                    </div>

                    <!-- 验证模式 -->
                    <div id="hash-verify-mode" class="hidden">
                        <h3 class="text-lg font-semibold text-gray-700 mb-3 flex items-center">
                            <i data-feather="check-square" class="w-5 h-5 mr-2"></i>
                            哈希验证
                        </h3>
                        <div class="space-y-3">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">输入内容:</label>
                                <textarea id="verify-input" class="w-full h-24 p-3 border border-gray-300 rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="要验证的内容..."></textarea>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">期望哈希值:</label>
                                <input type="text" id="expected-hash" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="输入期望的哈希值...">
                            </div>
                        </div>
                    </div>

                    <!-- 批量模式 -->
                    <div id="hash-batch-mode" class="hidden">
                        <h3 class="text-lg font-semibold text-gray-700 mb-3 flex items-center">
                            <i data-feather="list" class="w-5 h-5 mr-2"></i>
                            批量生成（每行一个）
                        </h3>
                        <textarea id="batch-input" class="w-full h-48 p-4 border border-gray-300 rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="请输入要批量处理的内容，每行一个..."></textarea>
                        <div class="mt-2 text-sm text-gray-500">
                            行数: <span id="batch-line-count">0</span> | 限制: 1000行
                        </div>
                    </div>
                </div>

                <!-- 输出区域 -->
                <div>
                    <h3 class="text-lg font-semibold text-gray-700 mb-3 flex items-center">
                        <i data-feather="code" class="w-5 h-5 mr-2"></i>
                        哈希结果
                    </h3>
                    <div id="hash-output" class="w-full h-48 p-4 bg-gray-50 border border-gray-300 rounded-lg font-mono text-sm overflow-auto"></div>
                    
                    <!-- 结果统计 -->
                    <div id="hash-stats" class="mt-4 text-sm text-gray-600 hidden">
                        <div class="grid grid-cols-2 gap-4">
                            <div>算法: <span id="result-algorithm" class="font-medium"></span></div>
                            <div>哈希长度: <span id="result-length" class="font-medium"></span></div>
                            <div>处理时间: <span id="result-time" class="font-medium"></span></div>
                            <div>输入大小: <span id="result-size" class="font-medium"></span></div>
                        </div>
                    </div>

                    <!-- 批量结果 -->
                    <div id="batch-results" class="mt-4 hidden">
                        <h4 class="text-md font-semibold text-gray-700 mb-2">处理结果</h4>
                        <div class="max-h-64 overflow-auto border border-gray-200 rounded-lg">
                            <table class="w-full text-sm">
                                <thead class="bg-gray-50">
                                    <tr>
                                        <th class="px-3 py-2 text-left">行号</th>
                                        <th class="px-3 py-2 text-left">输入</th>
                                        <th class="px-3 py-2 text-left">哈希值</th>
                                        <th class="px-3 py-2 text-left">状态</th>
                                    </tr>
                                </thead>
                                <tbody id="batch-results-body">
                                </tbody>
                            </table>
                        </div>
                        <div id="batch-summary" class="mt-2 text-sm text-gray-600"></div>
                    </div>

                    <!-- 文件对比结果 -->
                    <div id="compare-results" class="mt-4 hidden">
                        <h4 class="text-md font-semibold text-gray-700 mb-2">文件对比结果</h4>
                        <div id="compare-content" class="space-y-3"></div>
                    </div>
                </div>
            </div>

            <!-- 算法信息 -->
            <div id="algorithm-info" class="mt-6 bg-blue-50 border border-blue-200 rounded-lg p-4">
                <h3 class="text-lg font-semibold text-blue-800 mb-3 flex items-center">
                    <i data-feather="info" class="w-5 h-5 mr-2"></i>
                    算法信息
                </h3>
                <div id="algorithm-description" class="text-sm text-blue-700"></div>
            </div>

            <!-- 使用提示 -->
            <div class="bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 rounded-lg p-4 mt-6">
                <h3 class="text-lg font-semibold text-blue-800 mb-3 flex items-center">
                    <i data-feather="help-circle" class="w-5 h-5 mr-2"></i>
                    使用说明
                </h3>
                <div class="grid md:grid-cols-2 gap-4 text-sm text-blue-700">
                    <div>
                        <h4 class="font-semibold mb-2">主要功能</h4>
                        <ul class="space-y-1">
                            <li>• 文本哈希：生成文本的哈希值</li>
                            <li>• 文件哈希：计算文件完整性校验码</li>
                            <li>• 哈希验证：验证内容是否完整</li>
                            <li>• 批量生成：同时处理多个输入</li>
                        </ul>
                    </div>
                    <div>
                        <h4 class="font-semibold mb-2">算法选择</h4>
                        <ul class="space-y-1">
                            <li>• MD5：快速但安全性较低</li>
                            <li>• SHA-1：Git使用的算法</li>
                            <li>• SHA-256：推荐的安全算法</li>
                            <li>• SHA-512：最高安全性</li>
                        </ul>
                    </div>
                </div>
            </div>
        `;
    }

    static init() {
        // 获取元素
        const modeRadios = document.querySelectorAll('input[name="hash-mode"]');
        const algorithmSelect = document.getElementById('hash-algorithm');
        const hashInput = document.getElementById('hash-input');
        const hashFileInput = document.getElementById('hash-file-input');
        const hashFileDrop = document.getElementById('hash-file-drop');
        const verifyInput = document.getElementById('verify-input');
        const expectedHash = document.getElementById('expected-hash');
        const batchInput = document.getElementById('batch-input');
        const hashOutput = document.getElementById('hash-output');
        const hashStatus = document.getElementById('hash-status');
        
        // 按钮
        const generateBtn = document.getElementById('generate-hash');
        const verifyBtn = document.getElementById('verify-hash');
        const compareBtn = document.getElementById('compare-files');
        const copyBtn = document.getElementById('copy-hash');
        const clearBtn = document.getElementById('clear-hash');
        
        // 模式区域
        const textMode = document.getElementById('hash-text-mode');
        const fileMode = document.getElementById('hash-file-mode');
        const verifyMode = document.getElementById('hash-verify-mode');
        const batchMode = document.getElementById('hash-batch-mode');
        
        // 统计元素
        const hashStats = document.getElementById('hash-stats');
        const batchResults = document.getElementById('batch-results');
        const compareResults = document.getElementById('compare-results');
        const algorithmInfo = document.getElementById('algorithm-info');
        const algorithmDescription = document.getElementById('algorithm-description');

        let currentFile = null;
        let currentMode = 'text';
        let currentResult = '';

        // 更新状态显示
        const updateStatus = (status) => {
            hashStatus.textContent = status;
        };

        // 切换哈希模式
        const switchHashMode = (mode) => {
            // 隐藏所有模式
            textMode.classList.add('hidden');
            fileMode.classList.add('hidden');
            verifyMode.classList.add('hidden');
            batchMode.classList.add('hidden');
            
            // 显示对应模式
            switch (mode) {
                case 'text':
                    textMode.classList.remove('hidden');
                    break;
                case 'file':
                    fileMode.classList.remove('hidden');
                    break;
                case 'verify':
                    verifyMode.classList.remove('hidden');
                    break;
                case 'batch':
                    batchMode.classList.remove('hidden');
                    break;
            }
            
            clearHashResults();
        };

        // 清空哈希结果
        const clearHashResults = () => {
            hashOutput.textContent = '';
            hashStats.classList.add('hidden');
            batchResults.classList.add('hidden');
            compareResults.classList.add('hidden');
            copyBtn.disabled = true;
            currentResult = '';
        };

        // 更新算法信息
        const updateAlgorithmInfo = () => {
            const algorithm = algorithmSelect.value;
            const descriptions = {
                'md5': 'MD5是一种广泛使用的哈希函数，产生128位(16字节)的哈希值。虽然计算速度快，但安全性较低，主要用于数据完整性检查。',
                'sha1': 'SHA-1产生160位(20字节)的哈希值，曾被广泛使用，Git版本控制系统使用此算法。但现在已被认为不够安全。',
                'sha256': 'SHA-256是SHA-2系列中的一种，产生256位(32字节)的哈希值。目前被认为是安全的，被比特币等加密货币广泛使用。',
                'sha512': 'SHA-512产生512位(64字节)的哈希值，提供最高级别的安全性，适合对安全性要求极高的场景。'
            };
            algorithmDescription.textContent = descriptions[algorithm];
        };

        // 处理文件选择
        const handleFileSelect = (file) => {
            currentFile = file;
            document.getElementById('hash-file-name').textContent = file.name;
            document.getElementById('hash-file-size').textContent = DevToolsUtils.formatFileSize(file.size);
            document.getElementById('hash-file-info').classList.remove('hidden');
            updateStatus(`已选择文件: ${file.name}`);
        };

        // 生成哈希
        const generateHash = async () => {
            DevToolsUtils.addLoading(generateBtn);
            updateStatus('生成中...');
            
            try {
                const algorithm = algorithmSelect.value;
                let result;
                
                if (currentMode === 'text') {
                    const input = hashInput.value;
                    if (!input.trim()) {
                        DevToolsUtils.showToast('请输入要生成哈希的文本', 'error');
                        return;
                    }
                    result = await HashGenerator.generateTextHash(input, algorithm);
                } else if (currentMode === 'file') {
                    if (!currentFile) {
                        DevToolsUtils.showToast('请先选择文件', 'error');
                        return;
                    }
                    result = await HashGenerator.generateFileHash(currentFile, algorithm);
                } else if (currentMode === 'batch') {
                    const input = batchInput.value;
                    if (!input.trim()) {
                        DevToolsUtils.showToast('请输入要批量处理的内容', 'error');
                        return;
                    }
                    result = await HashGenerator.generateBatchHash(input, algorithm);
                }
                
                if (result && result.success) {
                    if (currentMode === 'batch') {
                        displayBatchResults(result.data);
                    } else {
                        displayHashResult(result.data);
                    }
                    currentResult = result.data.hash || result.data;
                    copyBtn.disabled = false;
                    updateStatus('生成完成');
                    DevToolsUtils.showToast('哈希生成成功！');
                } else {
                    DevToolsUtils.showToast(result.error || '生成哈希失败', 'error');
                    updateStatus('生成失败');
                }
            } catch (error) {
                DevToolsUtils.showToast('生成哈希时出错: ' + error.message, 'error');
                updateStatus('生成失败');
            } finally {
                DevToolsUtils.removeLoading(generateBtn);
            }
        };

        // 显示哈希结果
        const displayHashResult = (data) => {
            hashOutput.textContent = data.hash;
            
            // 显示统计信息
            document.getElementById('result-algorithm').textContent = data.algorithm.toUpperCase();
            document.getElementById('result-length').textContent = data.hash.length + ' 字符';
            document.getElementById('result-time').textContent = data.time + ' ms';
            document.getElementById('result-size').textContent = DevToolsUtils.formatFileSize(data.inputSize);
            hashStats.classList.remove('hidden');
        };

        // 显示批量结果
        const displayBatchResults = (data) => {
            const tbody = document.getElementById('batch-results-body');
            tbody.innerHTML = '';
            
            data.results.forEach((item, index) => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td class="px-3 py-2">${index + 1}</td>
                    <td class="px-3 py-2 font-mono text-xs">${item.input.length > 20 ? item.input.substring(0, 20) + '...' : item.input}</td>
                    <td class="px-3 py-2 font-mono text-xs">${item.success ? item.hash : '失败'}</td>
                    <td class="px-3 py-2">
                        <span class="px-2 py-1 text-xs rounded ${item.success ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}">
                            ${item.success ? '成功' : '失败'}
                        </span>
                    </td>
                `;
                tbody.appendChild(row);
            });
            
            document.getElementById('batch-summary').textContent = 
                `总计: ${data.results.length} 项，成功: ${data.summary.success} 项，失败: ${data.summary.failed} 项`;
            batchResults.classList.remove('hidden');
        };

        // 验证哈希
        const verifyHash = async () => {
            const input = verifyInput.value.trim();
            const expected = expectedHash.value.trim();
            
            if (!input || !expected) {
                DevToolsUtils.showToast('请填写要验证的内容和期望哈希值', 'error');
                return;
            }
            
            DevToolsUtils.addLoading(verifyBtn);
            updateStatus('验证中...');
            
            try {
                const algorithm = algorithmSelect.value;
                const result = await HashGenerator.verifyHash(input, expected, algorithm);
                
                if (result.success) {
                    if (result.data.match) {
                        hashOutput.innerHTML = `
                            <div class="text-green-600 font-semibold">✓ 哈希验证通过</div>
                            <div class="mt-2">
                                <div>算法: ${algorithm.toUpperCase()}</div>
                                <div>计算哈希: ${result.data.computed}</div>
                                <div>期望哈希: ${expected}</div>
                            </div>
                        `;
                        DevToolsUtils.showToast('哈希验证通过！', 'success');
                    } else {
                        hashOutput.innerHTML = `
                            <div class="text-red-600 font-semibold">✗ 哈希验证失败</div>
                            <div class="mt-2">
                                <div>算法: ${algorithm.toUpperCase()}</div>
                                <div>计算哈希: ${result.data.computed}</div>
                                <div>期望哈希: ${expected}</div>
                            </div>
                        `;
                        DevToolsUtils.showToast('哈希验证失败！', 'error');
                    }
                    updateStatus('验证完成');
                    currentResult = result.data.computed;
                    copyBtn.disabled = false;
                } else {
                    DevToolsUtils.showToast(result.error, 'error');
                    updateStatus('验证失败');
                }
            } catch (error) {
                DevToolsUtils.showToast('验证时出错: ' + error.message, 'error');
                updateStatus('验证失败');
            } finally {
                DevToolsUtils.removeLoading(verifyBtn);
            }
        };

        // 复制结果
        const copyHashResult = async () => {
            if (currentResult) {
                await DevToolsUtils.copyToClipboard(currentResult);
                DevToolsUtils.showToast('已复制到剪贴板！');
            } else {
                DevToolsUtils.showToast('没有可复制的内容', 'error');
            }
        };

        // 清空所有内容
        const clearHashAll = () => {
            hashInput.value = '';
            verifyInput.value = '';
            expectedHash.value = '';
            batchInput.value = '';
            currentFile = null;
            document.getElementById('hash-file-info').classList.add('hidden');
            document.getElementById('hash-input-count').textContent = '0';
            document.getElementById('batch-line-count').textContent = '0';
            clearHashResults();
            updateStatus('就绪');
        };

        // 事件监听器
        modeRadios.forEach(radio => {
            radio.addEventListener('change', () => {
                currentMode = radio.value;
                switchHashMode(radio.value);
                updateStatus(`切换到${radio.nextElementSibling.textContent}模式`);
            });
        });

        algorithmSelect.addEventListener('change', updateAlgorithmInfo);

        hashInput.addEventListener('input', () => {
            document.getElementById('hash-input-count').textContent = hashInput.value.length;
        });

        batchInput.addEventListener('input', () => {
            const lines = batchInput.value.split('\n').filter(line => line.trim()).length;
            document.getElementById('batch-line-count').textContent = lines;
        });

        // 文件拖拽处理
        hashFileDrop.addEventListener('click', () => {
            hashFileInput.click();
        });

        hashFileDrop.addEventListener('dragover', (e) => {
            e.preventDefault();
            hashFileDrop.classList.add('border-blue-500', 'bg-blue-50');
        });

        hashFileDrop.addEventListener('dragleave', (e) => {
            e.preventDefault();
            hashFileDrop.classList.remove('border-blue-500', 'bg-blue-50');
        });

        hashFileDrop.addEventListener('drop', (e) => {
            e.preventDefault();
            hashFileDrop.classList.remove('border-blue-500', 'bg-blue-50');
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                handleFileSelect(files[0]);
            }
        });

        hashFileInput.addEventListener('change', (e) => {
            if (e.target.files.length > 0) {
                handleFileSelect(e.target.files[0]);
            }
        });

        // 按钮事件
        generateBtn.addEventListener('click', generateHash);
        verifyBtn.addEventListener('click', verifyHash);
        copyBtn.addEventListener('click', copyHashResult);
        clearBtn.addEventListener('click', clearHashAll);

        // 快捷键
        hashInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && e.ctrlKey) {
                generateHash();
            }
        });

        verifyInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && e.ctrlKey) {
                verifyHash();
            }
        });

        batchInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && e.ctrlKey) {
                generateHash();
            }
        });

        // 初始化
        updateAlgorithmInfo();
        updateStatus('就绪');
        
        // 初始化 Feather 图标
        setTimeout(() => {
            if (typeof feather !== 'undefined') {
                feather.replace();
            }
        }, 100);
    }
};